import 'package:OASys/api/UserApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/UserVo.dart';
import 'package:OASys/utils/strUtils.dart';
import 'package:OASys/views/icon/myIcons.dart';
import 'package:flutter/material.dart';
import 'package:toast/toast.dart';

class UserPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScaffoldItem('用户管理', MyUserPage());
  }
}

class MyUserPage extends StatefulWidget {
  @override
  _MyUserPageState createState() => _MyUserPageState();
}

class _MyUserPageState extends State<MyUserPage>
    with SingleTickerProviderStateMixin {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  double _addPadding = 30;
  double _queryPadding = 30;
  bool flag = false;
  IconData actionIcon = MyIcons.spread;
  int page = 1;
  int limit = 10;
  int total = 0;
  List<UserVo> userVoList = [];
  String loadText = "加载更多";

  final Color disableColor = Color.fromRGBO(230, 162, 60, 1);
  final Color enableColor = Color.fromRGBO(76, 175, 80, 1);
  final String disableText = "禁用";
  final String enableText = "启用";

  UserVo andQuery = new UserVo();
  AnimationController _controller;
  @override
  void initState() {
    super.initState();
    getList();
    _controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 500))
          ..addListener(() {
            setState(() {
              _addPadding = 30 + 100 * _controller.value;
              _queryPadding = 30 + 200 * _controller.value;
            });
          });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  // 重置分页查询条件
  void resetQuertData() {
    setState(() {
      loadText = "加载更多";
      page = 1;
      limit = 10;
      total = 0;
    });
  }

  // 更新数据
  void updateData() {
    setState(() {
      resetQuertData();
      getList();
    });
  }

  // 获取用户列表
  void getList() {
    UserApi().list(1, 10, success: (res) {
      setState(() {
        userVoList = res;
        total += res.length;
        page++;
        userVoList.forEach((element) {
          print(element.toJson());
        });
      });
    }, error: (e) {
      print(e);
    });
  }

  // 查询用户
  void doQuery(context) {
    var form = formKey.currentState;
    form.save();
    print(andQuery.toJson());
    if (StrUtils.isBlank(andQuery.phone) &&
        StrUtils.isBlank(andQuery.nickname)) {
      Toast.show(
        '请输入查询条件',
        context,
        gravity: Toast.CENTER,
        duration: 2,
      );
    } else {
      setState(() {
        if (StrUtils.isBlank(andQuery.phone)) {
          andQuery.phone = null;
        }
        if (StrUtils.isBlank(andQuery.nickname)) {
          andQuery.nickname = null;
        }
      });
      resetQuertData();
      UserApi().list(
        page,
        limit,
        andQuery: andQuery,
        success: (res) {
          setState(() {
            userVoList = res;
            total += res.length;
            page++;
          });

          userVoList.forEach((element) {
            print(element.toJson());
          });
        },
        error: (err) {
          print(err.code);
          print(err.message);
          showMessage(context, err.message);
        },
      );
      Navigator.of(context, rootNavigator: true).pop();
    }
  }

  //重置表单
  void reset() {
    var form = formKey.currentState;
    form.reset();
    print('reset');
  }

  // 跳转修改用户信息
  Future toEdit(UserVo item) async {
    print('修改');
    Navigator.of(context, rootNavigator: true).pop();
    var result = await Navigator.of(context)
        .pushNamed('/userInfoEdit', arguments: item.toJson());
    if (result == null || !result) {
      print('未保存');
    } else {
      updateData();
      print('保存成功');
    }
  }

  //跳转添加页面
  Future toAdd() async {
    print("添加");
    var result =
        await Navigator.of(context).pushNamed("/userAdd", arguments: null);
    if (result == null || !result) {
      print('未添加');
    } else {
      updateData();
      print('添加成功');
    }
  }

  void doRemove(int id) {
    print('doRemove');
    UserApi().remove(
      id,
      success: (res) {
        showMessage(context, '删除成功');
        Navigator.of(context, rootNavigator: true).pop();
        updateData();
      },
      error: (err) {
        showMessage(context, err.message);
      },
    );
  }

  // 禁用或启用
  void setStatus(int id, int status) {
    UserApi().setStatus(
      id,
      status,
      success: (res) {
        Navigator.of(context, rootNavigator: true).pop();
        showSuccessMessage(context);
        updateData();
      },
      error: (err) {
        print(err.code);
        showMessage(context, err.message);
      },
    );
  }

  // 加载更多
  void doLoad() {
    UserApi().list(
      page,
      limit,
      andQuery: andQuery,
      success: (res) {
        if (res == null || res.length == 0) {
          print('无数据');
          setState(() {
            loadText = "没有更多了";
          });
          return;
        }
        setState(() {
          userVoList.addAll(res);
          total += res.length;
          page++;
          loadText = "加载更多";
        });
        userVoList.forEach((element) {
          print(element.toJson());
        });
      },
      error: (err) {
        print(err.code);
        print(err.message);
        showMessage(context, err.message);
      },
    );
  }

  // 显示搜索框
  showQuery() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            title: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                '查询用户',
                style: TextStyle(color: Colors.white),
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(3),
                  topRight: Radius.circular(3),
                ),
              ),
            ),
            contentPadding: EdgeInsets.all(0),
            content: Container(
              height: 300,
              width: 300,
              decoration: BoxDecoration(
                color: Color.fromRGBO(250, 250, 250, 1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Container(
                margin: EdgeInsets.only(
                  top: 20,
                  bottom: 20,
                ),
                height: 260,
                width: 300,
                child: Form(
                  key: formKey,
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          PrefixContanier("昵称:"),
                          Container(
                            width: 200,
                            child: FormInput(
                              hintText: "请输入昵称",
                              onSave: (value) {
                                andQuery.nickname = value;
                              },
                            ),
                          )
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          PrefixContanier("手机号码:"),
                          Container(
                            width: 200,
                            child: FormInput(
                              hintText: "请输入手机号码",
                              onSave: (value) {
                                andQuery.phone = value;
                              },
                            ),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
            actions: <Widget>[
              RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text('查 询'),
                onPressed: () {
                  doQuery(context);
                },
              ),
              RaisedButton(
                color: Color.fromRGBO(245, 108, 108, 1),
                child: Text('重 置'),
                onPressed: reset,
              ),
            ],
          );
        });
  }

  /// 显示用户信息卡片
  onClick(UserVo item) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '用户信息',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(
                  children: [
                    InfoItem(
                        '用户名',
                        StrUtils.isNotBlank(item.username)
                            ? item.username
                            : "无"),
                    SizedBox(height: 5),
                    InfoItem('昵称', item.nickname),
                    SizedBox(height: 5),
                    InfoItem(
                        '状态',
                        StrUtils.isBlank(item.statusName)
                            ? "无"
                            : item.statusName),
                    SizedBox(height: 5),
                    InfoItem(
                        '职位',
                        StrUtils.isNotBlank(item.personnelName)
                            ? item.personnelName
                            : "无"),
                    SizedBox(height: 5),
                    InfoItem('角色', '员工'),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            RaisedButton(
              color: Color.fromRGBO(33, 150, 243, 1),
              child: Text('修 改'),
              onPressed: () {
                toEdit(item);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('删 除'),
              onPressed: () {
                doRemove(item.id);
              },
            ),
            RaisedButton(
              color: item.status == 0 ? disableColor : enableColor,
              child: Text(item.status == 0 ? disableText : enableText,
                  style: TextStyle(color: Colors.white)),
              onPressed: () {
                setStatus(item.id, item.status == 0 ? 1 : 0);
              },
            ),
          ],
        );
      },
    );
  }

  // 按钮展开和收缩
  shrinkage() {
    setState(() {
      flag = !flag;
      if (flag) {
        actionIcon = MyIcons.shrink;
        _controller.forward();
      } else {
        actionIcon = MyIcons.spread;
        _controller.reverse();
      }
    });
  }

  /// 构建卡片
  Widget buildListItem(int index) {
    return FlatButton(
      child: Card(
        child: ListTile(
          title: Text(StrUtils.isNotBlank(userVoList[index].nickname)
              ? userVoList[index].nickname
              : "无"),
          subtitle: Text(StrUtils.isNotBlank(userVoList[index].phone)
              ? userVoList[index].phone
              : "无"),
        ),
      ),
      onPressed: () {
        onClick(userVoList[index]);
      },
    );
  }

  //构建加载更多
  Widget buildLoadMore() {
    return FlatButton(
      child: Container(
        child: Text(
          loadText,
          style: TextStyle(color: Colors.blue, fontSize: 12),
        ),
      ),
      onPressed: () {
        doLoad();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          padding: EdgeInsets.only(top: 10, bottom: 10),
          height: 720,
          child: ListView.builder(
            itemCount: total + 1,
            itemBuilder: (BuildContext context, int index) {
              if (index == total) {
                return buildLoadMore();
              }
              return buildListItem(index);
            },
          ),
        ),
        Positioned(
          right: _queryPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.yellow,
              child: Icon(
                MyIcons.query,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: showQuery,
            ),
          ),
        ),
        Positioned(
          right: _addPadding,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.green,
              child: Icon(
                MyIcons.add,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: toAdd,
            ),
          ),
        ),
        Positioned(
          right: 30,
          bottom: 30,
          child: Container(
            width: 68,
            height: 68,
            child: RaisedButton(
              color: Colors.blue,
              child: Icon(
                actionIcon,
                color: Colors.white,
                size: 30,
              ),
              shape: CircleBorder(),
              onPressed: shrinkage,
            ),
          ),
        ),
      ],
    );
  }
}
